package no.ntnu.item.ttm4115.termproject.gpsagent;

import java.io.InputStream;
import java.util.Enumeration;
import no.ntnu.item.ttm4115.termproject.gpsagent.data.GpsReadNew;
import javax.comm.SerialPort;
import java.util.List;
import no.ntnu.item.ttm4115.termproject.gpsagent.data.GpsRead;
import javax.comm.CommPortIdentifier;
import no.tellu.common.actorframe.ActorSM;

public class GpsAgentSM extends ActorSM {


    public GpsRead gpsRead;
    public CommPortIdentifier portId;
    public Enumeration portList;
    public List dataList;
    public InputStream inputStream;
    public SerialPort serialPort;
    public GpsReadNew gpsReadNew;
    static public double longi;
    static public double lati;


    /*
     * This method initializes the fields of the state machine.
     * You can edit this method inside the method body.
     * When the method is generated again, your part is copied.
     * Do not add any other methods in this class, they are not copied.
     */
    public void initialize(){
    	// gpsRead = new GpsRead();
    	
    	//gpsReadNew = new GpsReadNew ();
  	
		try{
			System.setProperty("driver", "gnu.io.RXTXCommDriver");
			//System.setProperty("-Djava.library.path",".");
			// copy rxtxSerial.dll to the ..\jredirectory\bin
			System.loadLibrary("rxtxSerial");

		}
		catch(Exception e){
			System.err.println("Err: in loading properties");
		}
		
		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) {
			System.out.println("er inne i while");
			portId = (CommPortIdentifier) portList.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				if (portId.getName().equals("COM2")) {
					
					// start thread

					break;
				}
			}
		}
		
		// open port
		try {
			System.out.println("opner port");
			serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
			
			try {
				serialPort.setSerialPortParams(38400,
						SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1,
						SerialPort.PARITY_NONE);
			} catch (javax.comm.UnsupportedCommOperationException e) {System.out.println(e);}
		} catch (javax.comm.PortInUseException e) {
			serialPort.close();
			System.out.println("Port in use ..i will stop now...restart your application");
			System.out.println(e);
		}
    }
}
